﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Finance;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Finance;
using TomNet.IMSC.Model.ViewModels;
using TomNet.IMSC.Web.Areas.Finance.Models;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;
using TomNet.IMSC.Core.Contracts.Account;

namespace TomNet.IMSC.Web.Areas.Finance.Controllers
{
    [Description("管理-金融商贷流水")]
    public class BusinessLoanController : BaseController
    {
        public IFinanceBusinessLoanRunningsContract BusiLoanContract { get; set; }//商贷
        public IFinanceRunningsExpandTimeContract ExpContract { get; set; }//延时
        public IFinanceRunningsContract Contract { get; set; }//主表 流水
        public IStaffContract StaffContract { get; set; }//业务销售人员
        public IBrokerageRunningsContract BrokerageContract { set; get; }//应缴费用

        public IUsersContract UserContract { get; set; }//经纪人表
        public IImagesContract ImageContrat { set; get; }



        LoginModel loginModel = Common.CookiesManagement.GetLoginModel(Common.CookiesManagement.GetTicket(Common.CookiesManagement.GetCookies()));

        [Description("管理-金融商贷流水")]
        public ActionResult Index()
        {
            return View();
        }

        [Description("管理-金融商贷流水")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult IndexAsync(int pageIndex, int pageSize, DateTime beginDate, DateTime endDate, string searchLimit, string searcgKey, string keyLimit
            , string runningState = "0", string progressState = "0", string progress = "0")//, int depid
        {
            endDate = endDate.AddDays(1);

            UpdateLoginModelAuthorityIds(loginModel);
            //Contract.Entities.Where(x => x.SellStaffID == loginModel.Id || x.TransactStaffID == loginModel.Id);
            //new delegate (GetProgressState);// 

            var query = (from m in Contract.Entities
                         join b in BusiLoanContract.Entities on m.Id equals b.FinanceRunningsID into l
                         from tt in l.DefaultIfEmpty()
                         where m.FinanceItemsID == (int)LoanType.商业贷款 && m.FilingTime >= beginDate && m.FilingTime < endDate
                         select new FinanceRunningViewModel
                         {
                             Id = m.Id,
                             State = m.State,
                             IntermediaryName = m.IntermediaryName,
                             UserName = m.UserName,
                             UserPhone = m.UserPhone,
                             CustomerName = m.CustomerName == null ? "" : m.CustomerName,
                             CustomerPhone = m.CustomerPhone == null ? "" : m.CustomerPhone,
                             TransferDetailed = m.TransferDetailed,
                             BuildingName = m.BuildingName,
                             Address = m.Address,
                             Price = m.Price,
                             Area = m.Area,

                             HouseOwnerName = m.HouseOwnerName,
                             HouseOwnerPhone = m.HouseOwnerPhone,
                             FilingTime = m.FilingTime,
                             FilingState = m.FilingState,
                             //CollectDataTime = m.CollectDataTime,
                             CollectDataState = m.CollectDataState,

                             FilingAuditingTime = m.FilingAuditingTime,// 报备审批时间
                             //ContractTime = tt.ContractTime,
                             ContractState = tt.ContractState,

                             //ApproveTime = tt.ApproveTime,
                             ApproveState = tt.ApproveState,

                             //ProvideTime = tt.ProvideTime,
                             ProvideState = tt.ProvideState,

                             SellStaffID = m.SellStaffID,
                             SellStaffName = m.SellStaffID == 0 ? "" : StaffContract.Entities.Where(x => x.Id == m.SellStaffID).FirstOrDefault().Name,
                             TransactStaffName = m.TransactStaffID == 0 ? "" : StaffContract.Entities.Where(x => x.Id == m.TransactStaffID).FirstOrDefault().Name,
                             TransactStaffID = m.TransactStaffID,

                             //ProgressState = m.FilingState.ToString(),
                             Progress = m.Progress,
                             Remark = m.Remark,

                             //ProgressState = func(m,tt).Name,
                         });
            if (!loginModel.AuthorityIds.Split(',').Contains("294"))
            {
                query = query.Where(x => x.SellStaffID == loginModel.Id || x.TransactStaffID == loginModel.Id);
            }

            if (string.IsNullOrEmpty(keyLimit) && !string.IsNullOrEmpty(searchLimit))
            {
                query = query.Where(m => m.CustomerName.Contains(searchLimit) || m.CustomerPhone.Contains(searchLimit) || m.IntermediaryName.Contains(searchLimit)
                || m.UserName.Contains(searchLimit) || m.SellStaffName.Contains(searchLimit) || m.TransactStaffName.Contains(searchLimit)
                || m.Id.ToString().Contains(searchLimit));//服务类型、流水号
            }

            var where = PredicateBuilder.True<FinanceRunningViewModel>();
            if (!string.IsNullOrEmpty(keyLimit) && !string.IsNullOrEmpty(searchLimit))
            {
                switch (keyLimit)
                {
                    case "cName":
                        where = where.And(p => p.CustomerName.Contains(searchLimit));
                        break;
                    case "cPhone":
                        where = where.And(p => p.CustomerPhone.Contains(searchLimit));
                        break;
                    case "iName":
                        where = where.And(p => p.IntermediaryName.Contains(searchLimit));
                        break;
                    case "uName":
                        where = where.And(p => p.UserName.Contains(searchLimit));
                        break;
                    case "sName":
                        where = where.And(p => p.SellStaffName.Contains(searchLimit));
                        break;
                    case "tName":
                        where = where.And(p => p.TransactStaffName.Contains(searchLimit));
                        break;
                    case "sType":

                        break;
                    case "rId":
                        where = where.And(p => p.Id.ToString().Contains(searchLimit));
                        break;

                }
            }

            if (runningState != "0")
            {
                int a = Convert.ToInt32(runningState);
                where = where.And(m => m.State.Equals(a));
            }
            if (progress != "0")
            {
                where = where.And(m => m.Progress.ToString().Equals(progress));
            }
            if (progressState != "-1")//操作状态//待分配
            {
                int pstate = Convert.ToInt32(progressState);
                //where = where.And(m => (m.Progress == 1 && m.FilingState == pstate)
                //            || (m.Progress == 2 && m.CollectDataState == pstate)
                //            || (m.Progress == 2 && m.TransactStaffID == 0 && m.CollectDataState == pstate)//待分配 办件人
                //            || (m.Progress == 2 && m.TransactStaffID != 0 && m.CollectDataState == pstate)//已分配 办件人
                //            || (m.Progress == 3 && m.ContractState == pstate)
                //            || (m.Progress == 4 && m.ApproveState == pstate)
                //            || (m.Progress == 5 && m.ProvideState == pstate));

                //where = where.And(m => (m.Progress == 1 ? m.FilingState == pstate :
                //    (m.Progress == 2 ? m.CollectDataState == pstate
                //        : (m.Progress == 3 ? m.ContractState == pstate
                //            : (m.Progress == 4 ? m.ApproveState == pstate
                //                : (m.Progress == 5 ? m.ProvideState == pstate : false))))));


                switch ((Progress_State)Enum.ToObject(typeof(Progress_State), pstate))
                {
                    case Progress_State.待分配:
                        where = where.And(m => (m.Progress == 2 && m.CollectDataState == 0)
                            || (m.Progress == 2 && m.TransactStaffID == 0 && m.CollectDataState == 0)//人员待分配
                            || (m.Progress == 3 && m.ContractState == 0)
                            || (m.Progress == 4 && m.ApproveState == 0)
                            || (m.Progress == 5 && m.ProvideState == 0));
                        break;
                    case Progress_State.进行中:
                        where = where.And(m => (m.Progress == 1 && m.FilingState == 1)//报备进行中
                            || (m.Progress == 1 && m.CollectDataState == 1)//资料收集中
                            || (m.Progress == 2 && m.ContractState == 1)//面签进行中
                            || (m.Progress == 3 && m.ApproveState == 1)//审批进行中
                            || (m.Progress == 4 && m.ProvideState == 1)//放款进行中
                            || (m.Progress == 4 && m.ApproveState == 2 && m.ProvideState == 1));//审批完成 同时放款进行中
                                                                                                //|| (m.Progress == 5 && m.ProvideState == 1)
                        break;
                    case Progress_State.已完成:
                        where = where.And(m => (m.Progress == 1 && m.FilingState == 2)
                            //|| (m.Progress == 2 && m.CollectDataState == 2 && m.TransactStaffID != 0)
                            || (m.Progress == 3 && m.ContractState == 2)//面签
                            || (m.Progress == 4 && m.ApproveState == 2)//审批完成 同时放款进行中
                            || (m.Progress == 5 && m.ProvideState == 2));//放款完成
                        break;
                    case Progress_State.已终止:
                        where = where.And(m => (m.Progress == 1 && m.FilingState == 3)
                            || (m.Progress == 2 && m.CollectDataState == 3)//收集资料，不能被终止
                            || (m.Progress == 3 && m.ContractState == 3)
                            || (m.Progress == 4 && m.ApproveState == 3)
                            || (m.Progress == 5 && m.ProvideState == 3));
                        break;
                    default:
                        break;
                }
            }

            query = query.Where(where.Compile()).AsQueryable();

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.FilingTime);


            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<FinanceRunningViewModel>().AsQueryable();
            List<FinanceRunningViewModel> _list = query.ToList();
            foreach (FinanceRunningViewModel item in _list)
            {
                BaseRemark obj = GetProgressState(Contract.GetByKey(item.Id), BusiLoanContract.Entities.Where(x => x.FinanceRunningsID == item.Id).FirstOrDefault());
                item.ProgressState = obj.Name;// ((BusinessLoanProgress)(obj.Id + 1)).ToString();
                item.ProgressTime = obj.Value == null ? "" : Convert.ToDateTime(obj.Value).ToString("yyyy-MM-dd HH:mm");
                item.ProgressTitle = obj.Remark;
                var q = ExpContract.Entities.Where(x => !x.IsDeleted && x.FinanceRunningsID == item.Id && x.Progress == item.Progress && x.State == 1).FirstOrDefault();
                item.DelayOption = q != null ? q.Id : 0;
            }

            GridData<FinanceRunningViewModel> gridData = new GridData<FinanceRunningViewModel>() { Total = total, Rows = _list };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 初始化-审批
        /// </summary>
        /// <param name="id"></param>
        /// <param name="curIdx"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        [Description("管理-金融商贷流水-初始化")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult ApprovalAsync(int id)
        {
            var result = new AjaxResult();
            try
            {
                FinanceRunnings entity = Contract.GetByKey(id);
                entity.TransactStaffID = 0;
                entity.State = 1;
                entity.Progress = 2;

                var query = BusiLoanContract.Entities.Where(x => x.FinanceRunningsID == id).FirstOrDefault();
                //.(m => m.Name.Equals(entity.Name) && m.Id != entity.Id);
                if (query == null)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "异常操作";
                }
                else
                {
                    query.LoanBank = "";
                    query.LoanYearNumber = 0;
                    query.LoanAmount = 0;

                    query.ContractState = 0;
                    query.ContractTime = DateTime.Now;
                    query.ContractRemark = "";
                    query.ContractStaffID = 0;

                    query.ApproveState = 0;
                    query.ApproveTime = DateTime.Now;
                    query.ApproveRemark = "";
                    query.ApproveStaffID = 0;

                    query.ProvideState = 0;
                    query.ProvideTime = DateTime.Now;
                    query.ProvideRemark = "";
                    query.ProvideStaffID = 0;

                    var count = Contract.Update(entity);
                    var connt2 = BusiLoanContract.Update(query);

                    int[] idsInt = ExpContract.Entities.Where(x => !x.IsDeleted && x.FinanceRunningsID == entity.Id).Select(x => x.Id).ToArray();
                    int count3 = 0;
                    if (idsInt.Count() > 0)
                    {
                        count3 = ExpContract.UpdateDirect(m => idsInt.Contains(m.Id), d => new FinanceRunningsExpandTime
                        {
                            IsDeleted = true,
                        });
                    }
                    else { count3 = 1; }

                    if (count > 0 && connt2 > 0 && count3 > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "初始化成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "初始化失败";
                    }
                }
                //int[] idsInt = ExpContract.Entities.Where(x=>x.FinanceRunningsID==entity.Id).Select(x=>x.Id).ToArray();
                ////string[] idsStr = ids.Split(new char[] { ',' });
                ////int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                //ExpContract.DeleteDirect(m => idsInt.Contains(m.Id));

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        #region 修改流水相关操作
        [Description("管理-金融商贷-编辑")]
        public ActionResult Edit(int id)
        {
            //本流水是否上传过图片

            var list = ImageContrat.Entities.Where(x => x.GroupID == 9 && x.InterfixID == id).Select(x => new BaseName { Name = x.ImagePath + x.FileName, Id = x.ImageType }).ToList();
            int images = list.Count();

            var entity = Contract.GetByKey(id);//主表
            var loanEntity = BusiLoanContract.Entities.Where(x => x.FinanceRunningsID == entity.Id).FirstOrDefault();
            var expEntity = ExpContract.Entities.Where(x => !x.IsDeleted && x.FinanceRunningsID == entity.Id && x.Progress == entity.Progress).FirstOrDefault();

            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewBag.FinanceDelay = ValidateExpEntity(entity, loanEntity, expEntity);

            ViewData["entity"] = entity;
            ViewData["attEntity"] = loanEntity;
            ViewData["expEntity"] = expEntity;
            ViewData["images"] = list.ToList();


            ViewBag.ImageCount = images;
            return View();
        }
        /// <summary>
        /// 0延时待审批 1提交申请 2同意申请
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="loanEntity"></param>
        /// <param name="ProgressIndex"></param>
        /// <returns></returns>
        private int ValidateExpEntity(FinanceRunnings entity, FinanceBusinessLoanRunnings loanEntity, FinanceRunningsExpandTime expEntity)
        {
            var currentIndex = GetProgressState(entity, loanEntity).Id;
            int on = -1;

            if (entity.Progress == (int)BusinessLoanProgress.审批
                || entity.Progress == (int)BusinessLoanProgress.放款
                || entity.Progress == (int)BusinessLoanProgress.面签
                || (entity.Progress == (int)BusinessLoanProgress.资料收集 && loanEntity.ContractState == 1))
            {
                switch (entity.Progress)
                {
                    case 2://收集资料
                        //curTime = loan.ContractTime;
                        if ((loanEntity.ContractTime.Date < DateTime.Now.Date && loanEntity.ContractState == 1 && expEntity == null) || (expEntity != null && expEntity.ExpandTime.Date < DateTime.Now.Date))
                        {
                            ViewBag.StepIdx = currentIndex - 1;
                            on = 1;
                        }
                        else if (expEntity != null && expEntity.ExpandTime.Date > DateTime.Now.Date && expEntity.State == 1)//延时待审批
                        {
                            ViewBag.StepIdx = currentIndex - 1;
                            on = 0;
                        }
                        else
                        {
                            ViewBag.StepIdx = currentIndex;
                        }

                        break;
                    case 3://面签
                        //curTime = loan.ApproveTime;
                        if ((loanEntity.ApproveTime.Date < DateTime.Now.Date && loanEntity.ApproveState == 1 && expEntity == null) || (expEntity != null && expEntity.ExpandTime.Date < DateTime.Now.Date))
                        {
                            ViewBag.StepIdx = currentIndex - 1;
                            on = 1;
                        }
                        else if (expEntity != null && expEntity.ExpandTime.Date > DateTime.Now.Date && expEntity.State == 1)//延时待审批
                        {
                            ViewBag.StepIdx = currentIndex - 1;
                            on = 0;
                        }
                        else
                        {
                            ViewBag.StepIdx = currentIndex;
                        }
                        break;
                    case 4://审批
                        //curTime = loan.ProvideTime;
                        if ((loanEntity.ProvideTime.Date < DateTime.Now.Date && loanEntity.ProvideState == 1 && expEntity == null) || (expEntity != null && expEntity.ExpandTime.Date < DateTime.Now.Date))
                        {
                            ViewBag.StepIdx = currentIndex - 1;
                            on = 1;
                        }
                        else if (expEntity != null && expEntity.ExpandTime.Date > DateTime.Now.Date && expEntity.State == 1)//延时待审批
                        {
                            ViewBag.StepIdx = currentIndex - 1;
                            on = 0;
                        }
                        else
                        {
                            ViewBag.StepIdx = currentIndex;
                        }
                        break;
                    case 5:

                        {
                            ViewBag.StepIdx = currentIndex;
                        }
                        break;
                }

                //show();                
            }
            else
            {//hide();
                ViewBag.StepIdx = currentIndex;
            }

            return on;
        }

        [Description("管理-金融商贷-编辑")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditAsync(int id, int curIdx, string str)
        {
            var result = new AjaxResult();
            try
            {
                FinanceRunnings item = Contract.GetByKey(id);
                var loanObj = BusiLoanContract.Entities.Where(x => x.FinanceRunningsID == item.Id).FirstOrDefault();
                if (item == null)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
                else
                {
                    string successResult = "操作成功";
                    Dictionary<string, string> obj = JsonBinder<Dictionary<string, string>>.JsonToObject(str);
                    if (curIdx == 0)//报备审核
                    {
                        item.CollectDataType = Convert.ToInt32(obj["CollectDataType"]);//
                        item.FilingAuditingRemark = obj["FilingAuditingRemark"];
                        item.FilingAuditingTime = DateTime.Now; //审批时间
                        if (Convert.ToInt32(obj["Option"]) == 1)//拒绝
                        {
                            item.State = 2;
                            item.FilingState = 3;
                        }
                        else
                        {
                            item.State = 1;
                            item.FilingState = 2;

                            //为下一步更改数据
                            item.CollectDataState = 1;
                        }
                        item.Progress = (int)PAProgress.报备审核;
                        item.FilingAuditingStaffID = loginModel.Id;//登录人的Id

                        successResult = "报备--操作成功";
                    }
                    else if (curIdx == 1 && loanObj != null)//填写资料
                    {// 小区名称、房屋地址、成交价格、成交面积、房主姓名、房主电话
                        item.BuildingName = obj["BuildingName"];
                        item.Address = obj["Address"];
                        item.Area = Convert.ToDecimal(obj["Area"]);
                        item.Price = Convert.ToDecimal(obj["Price"]);
                        item.HouseOwnerName = obj["HouseOwnerName"];
                        item.HouseOwnerPhone = obj["HouseOwnerPhone"];

                        //更改上一步数据

                        item.CollectDataTime = DateTime.Now;
                        item.CollectDataStaffID = loginModel.Id;
                        item.CollectDataRemark = obj["CollectDataRemark"];

                        if (Convert.ToInt32(obj["CollectDataHandle"]) == 1)//拒绝
                        {
                            item.State = 2;
                            item.CollectDataState = 3;                            
                        }
                        else
                        {
                            item.State = 1;
                            item.CollectDataState = 2;

                            BrokerageContract.InitBrokerage(5, item.Id);
                            BrokerageContract.InitSalary(5, item.Id);
                            ////为下一步更改数据
                            //item.CollectDataState = 1;
                        }

                        item.Progress = (int)PAProgress.资料收集;


                        //为下一步更改数据
                        loanObj.ContractState = 0;
                        successResult = "资料填写--操作成功";
                    }
                    else if (curIdx == 2 && loanObj != null)//分配办件人
                    {

                        loanObj.LoanAmount = Convert.ToDecimal(obj["LoanAmount"]);
                        loanObj.LoanYearNumber = Convert.ToInt32(obj["LoanYearNumber"]);
                        loanObj.LoanBank = obj["LoanBank"].Trim();
                        item.TransactStaffID = Convert.ToInt32(obj["TransactStaffID"]);//分配办件人

                        item.State = 1;
                        item.Progress = (int)BusinessLoanProgress.资料收集;
                        loanObj.ContractState = 0;

                        //更改上一步数据
                        //item.CollectDataState = 2;

                        //为下一步更改数据
                        loanObj.ContractStaffID = 0;//登录人的Id

                        successResult = "分配办件人--操作成功";
                    }

                    else if (curIdx == 3 && loanObj != null)//设置面签时间
                    {
                        loanObj.ContractTime = DateTime.Parse(obj["ContractTime"]);
                        loanObj.ContractRemark = obj["ContractRemark"];
                        item.Progress = (int)BusinessLoanProgress.资料收集;
                        //loanObj.ApproveState = 2;//上一步完成
                        //loanObj.ApproveStaffID = 0;//登录人的Id

                        //更改上一步数据


                        //为下一步更改数据
                        loanObj.ContractState = 1;
                        //loanObj.ContractStaffID = loginModel.Id;
                        successResult = "置面签时间--设置成功";
                    }
                    else if (curIdx == 4 && loanObj != null)//
                    {
                        loanObj.ContractRemark = obj["ContractRemark2"];
                        loanObj.ApproveTime = DateTime.Parse(obj["ApproveTime"]);//设置面签时间
                        loanObj.ApproveRemark = obj["ApproveRemark"];

                        if (Convert.ToInt32(obj["ContractHandle"]) == 1)//终止，面签失败
                        {
                            item.State = 2;
                            loanObj.ContractTime = DateTime.Now;//面签被拒绝时间
                            loanObj.ContractState = 3;
                        }
                        else
                        {
                            item.State = 1;
                            loanObj.ContractState = 2;
                            item.Progress = (int)BusinessLoanProgress.面签;

                            //更改上一步数据

                            //为下一步更改数据
                            loanObj.ApproveState = 1;
                        }
                        loanObj.ContractStaffID = loginModel.Id;//登录人的Id
                        successResult = "面签--操作成功";
                    }
                    else if (curIdx == 5 && loanObj != null)//
                    {
                        loanObj.ApproveRemark = obj["ApproveRemark2"];
                        loanObj.ProvideTime = DateTime.Parse(obj["ProvideTime"]);
                        loanObj.ProvideRemark = obj["ProvideRemark"];

                        if (Convert.ToInt32(obj["ApproveHandle"]) == 1)//终止，审批失败
                        {
                            item.State = 2;
                            loanObj.ApproveState = 3;
                            loanObj.ApproveTime = DateTime.Now;
                        }
                        else
                        {
                            item.State = 1;
                            //更改上一步数据

                            loanObj.ApproveState = 2;

                            //为下一步更改数据
                            item.Progress = (int)BusinessLoanProgress.审批;
                            loanObj.ProvideState = 1;
                        }
                        loanObj.ApproveStaffID = loginModel.Id;
                        successResult = "审批--操作成功";
                    }
                    else if (curIdx == 6 && loanObj != null)//
                    {
                        loanObj.ProvideRemark = obj["ProvideRemark2"];
                        if (Convert.ToInt32(obj["ProvideHandle"]) == 1)//
                        {
                            item.State = 2;
                            loanObj.ProvideTime = DateTime.Now;
                            loanObj.ProvideState = 3;
                        }
                        else
                        {
                            item.State = 3;
                            //更改上一步数据

                            //为下一步更改数据
                            item.Progress = (int)BusinessLoanProgress.放款;
                            loanObj.ProvideState = 2;
                        }
                        loanObj.ProvideStaffID = loginModel.Id;
                        successResult = "放款--操作成功";
                    }


                    var count = Contract.Update(item);
                    var count2 = BusiLoanContract.Update(loanObj);

                    if (count > 0 || count2 > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = successResult;
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "操作失败";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("管理-金融商贷-延时操作")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditAsync4ExpTime(int id, int curIdx, string str)
        {
            var result = new AjaxResult();
            try
            {
                FinanceRunningsExpandTime row = null;
                if (curIdx == -1)
                {
                    row = ExpContract.GetByKey(id);
                }
                else
                    row = ExpContract.Entities.Where(x => !x.IsDeleted && x.FinanceRunningsID == id && x.Progress == curIdx).FirstOrDefault();

                Dictionary<string, string> dic = JsonBinder<Dictionary<string, string>>.JsonToObject(str);
                if (row == null)
                {
                    FinanceRunningsExpandTime obj = new FinanceRunningsExpandTime()
                    {
                        CreatedTime = DateTime.Now,
                        ExpandTime = dic.Keys.Contains("time") ? DateTime.Parse(dic["time"]) : DateTime.Now,
                        FinanceRunningsID = id,
                        IsDeleted = false,
                        IsLocked = false,
                        Progress = curIdx,
                        //StaffID = loginModel.Id,
                        State = 1,
                    };

                    ExpContract.Insert(obj);
                }
                else
                {
                    if (dic.Keys.Contains("time"))
                    {
                        row.ExpandTime = DateTime.Parse(dic["time"]);
                    }
                    if (dic.Keys.Contains("state"))//进行审批
                    {
                        row.State = int.Parse(dic["state"]);
                        var loan = BusiLoanContract.Entities.Where(x => x.FinanceRunningsID == row.FinanceRunningsID).FirstOrDefault();
                        if (loan != null)
                        {
                            switch (row.Progress)
                            {
                                case (int)BusinessLoanProgress.面签:
                                    loan.ContractTime = row.ExpandTime;
                                    break;
                                case (int)BusinessLoanProgress.审批:
                                    loan.ApproveTime = row.ExpandTime;
                                    break;
                                case (int)BusinessLoanProgress.放款:
                                    loan.ProvideTime = row.ExpandTime;
                                    break;
                                default:
                                    break;
                            }
                            BusiLoanContract.Update(loan);
                        }
                        row.StaffID = loginModel.Id;
                    }
                    ExpContract.Update(row);
                }
                result.Type = AjaxResultType.Success;
                result.Content = "操作成功";

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        private static BaseRemark GetProgressState(FinanceRunnings entity, FinanceBusinessLoanRunnings loanEntity)
        {
            //拒绝时，显示当前操作时间
            BaseRemark stepIdx = new BaseRemark();

            if (entity.FilingState == 1)//报备待审核
            {
                stepIdx = new BaseRemark() { Id = 0, Name = "报备 待审核", Value = entity.FilingTime };//0;
            }
            else if (entity.FilingState == 3)//拒绝时，显示当前操作时间
            {
                stepIdx = new BaseRemark() { Id = 0, Name = "报备审核 " + Progress_State.已终止, Value = entity.FilingAuditingTime, Remark = entity.FilingAuditingRemark };//0;
            }
            else if (entity.FilingState == 2)
            {//报备审核已完成
             //stepIdx = new BaseName() { Id = 0, Name = "报备待审核" };//1;
                if (entity.CollectDataState == 1)//搜集资料待完成
                {
                    stepIdx = new BaseRemark() { Id = 1, Name = "资料收集 " + Progress_State.进行中, Value = entity.FilingAuditingTime, Remark = entity.FilingAuditingRemark };//1;
                }
                else if (entity.CollectDataState == 3)//资料不全，被终止
                {
                    stepIdx = new BaseRemark() { Id = 1, Name = "资料收集 " + Progress_State.已终止, Value = entity.CollectDataTime, Remark = entity.CollectDataRemark };//0;
                }
                else if (entity.CollectDataState == 2)////搜集资料已完成
                {
                    //stepIdx = new BaseRemark() { Id = 2, Name = "资料搜集 已完成", Value = frViewModel.FilingAuditingTime, Remark= entity.CollectDataRemark };//2;
                    if (loanEntity.ContractState == 0)//分配办件人
                    {
                        stepIdx = new BaseRemark() { Id = 2, Name = "办件人 " + Progress_State.待分配, Remark = entity.CollectDataRemark };//2;
                        if (entity.TransactStaffID != 0)
                        {
                            stepIdx = new BaseRemark() { Id = 3, Name = "办件人 已分配", Remark = loanEntity.ContractRemark };//3;
                        }
                    }
                    else if (loanEntity.ContractState == 1)
                    {
                        stepIdx = new BaseRemark() { Id = 4, Name = "面签 " + Progress_State.进行中, Value = loanEntity.ContractTime, Remark = loanEntity.ContractRemark };//4;
                    }
                    else if (loanEntity.ContractState == 3)
                    {
                        stepIdx = new BaseRemark() { Id = 4, Name = "面签 " + Progress_State.已终止, Value = loanEntity.ContractTime, Remark = loanEntity.ContractRemark };//4;
                    }
                    else if (loanEntity.ContractState == 2)
                    {
                        //stepIdx = new BaseRemark() { Id = 5, Name = "面签 已完成", Value = loanEntity.ContractTime, Remark = loanEntity.ApproveRemark };//5;
                        if (loanEntity.ApproveState == 1)//审批进行中
                        {
                            stepIdx = new BaseRemark() { Id = 5, Name = "面签 " + Progress_State.已完成, Value = loanEntity.ContractTime, Remark = loanEntity.ProvideRemark };//5;
                        }
                        else if (loanEntity.ApproveState == 3)
                        {
                            stepIdx = new BaseRemark() { Id = 5, Name = "审批 " + Progress_State.已终止, Value = loanEntity.ApproveTime, Remark = loanEntity.ProvideRemark };//5;
                        }
                        else if (loanEntity.ApproveState == 2)
                        {
                            //stepIdx = new BaseRemark() { Id = 6, Name = "审批 已完成", Value = loanEntity.ApproveTime, Remark = loanEntity.ProvideRemark };//6;
                            if (loanEntity.ProvideState == 1)
                            {
                                stepIdx = new BaseRemark() { Id = 6, Name = "放款 " + Progress_State.进行中, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };//6;
                            }
                            else if (loanEntity.ProvideState == 2)
                            {
                                stepIdx = new BaseRemark() { Id = 7, Name = "放款 " + Progress_State.已完成, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };// 7;
                            }
                            else if (loanEntity.ProvideState == 3)
                            {
                                stepIdx = new BaseRemark() { Id = 7, Name = "放款 " + Progress_State.已终止, Value = loanEntity.ProvideTime, Remark = loanEntity.ProvideRemark };//7;
                            }
                        }
                    }
                }
            }

            return stepIdx;

        }


        #endregion


        [Description("管理-金融代办员-列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetUserAsync()
        {
            var result = new AjaxResult();
            try
            {
                var list = UserContract.Entities.Select(x => new BaseName() { Name = x.Name, Id = x.Id });
                //var count = Contract.Update(item);
                if (list.Count() > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Data = list;
                    result.Content = "成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "失败";
                }
                //}
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        Expression<Func<FinanceRunnings, FinanceBusinessLoanRunnings, int>> exp;

        Func<FinanceRunnings, FinanceBusinessLoanRunnings, BaseRemark> func = (obj1, obj2) =>
        {
            return GetProgressState(obj1, obj2); ;
        };
        public delegate TResult Funex<in T1, in T2, out TResult>(T1 t1, T2 t2);
    }
}